﻿using AnChao.WPF.Controls.MDI.Core;
using System;
using System.Collections;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;


namespace CRootGUI.Controls
{
    public class TabItemDraggable : TabItem
    {
        public TabItemDraggable()
        {
           
            this.Drop += TabItemDraggable_Drop;
        }       


       
        public System.Windows.Controls.TabControl OriParent { get; set; }


        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

        }

        public void SingleWindow(object sender, RoutedEventArgs e)
        {
            try
            {
                var parent = TabControlParent;
                var target = parent.ItemContainerGenerator.ItemFromContainer(this);

                IList list;
                if (parent.ItemsSource != null)
                {
                    list = parent.ItemsSource as IList;
                }
                else
                {
                    list = parent.Items;
                }
                list.Remove(target);

                if (this.OriParent == null)
                {
                    this.OriParent = parent;
                }

                Window win = new Window();
                win.Content = this.Content;
                win.Width = 300;
                win.Height = 300;
                win.Tag = parent;
                win.Closed += Win_Closed;
                win.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                win.Show();
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void Win_Closed(object sender, EventArgs e)
        {
            try
            {
                Window win = sender as Window;

                if (win != null && win.Tag != null)
                {
                    TabControl parent = win.Tag as TabControl;
                    parent.Items.Add(this);

                    IList list;
                    if (parent.ItemsSource != null)
                    {
                        list = parent.ItemsSource as IList;
                    }
                    else
                    {
                        list = parent.Items;
                    }
                    int index = list.IndexOf(this);

                    parent.SelectedIndex = index;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private System.Windows.Controls.TabControl TabControlParent => System.Windows.Controls.ItemsControl.ItemsControlFromItemContainer(this) as System.Windows.Controls.TabControl;

        protected override void OnMouseRightButtonDown(MouseButtonEventArgs e)
        {
            base.OnMouseRightButtonDown(e);
            IsSelected = true;
            Focus();
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);

            var bMouseDown = e.LeftButton == MouseButtonState.Pressed;
            if (!bMouseDown)
                return;

            var pos = e.GetPosition(this);
            HitTestResult result = VisualTreeHelper.HitTest(this, pos);
            if (result == null)
            {
                return;
            }
            var dragItem = ViewHelper.FindParent<Window>(result.VisualHit);
            if (dragItem == null)
            {
                return;
            }

            DragDrop.DoDragDrop(this, this, DragDropEffects.Move);
        }

        private void TabItemDraggable_Drop(object sender, DragEventArgs e)
        {
            var parent = TabControlParent;
            if (parent == null) return;

            //查找元数据
            var sourceItem = e.Data.GetData(typeof(TabItemDraggable)) as TabItemDraggable;
            if (sourceItem == null)
            {
                return;
            }

            var targetItem = this;
            if (sourceItem == targetItem)
            {
                return;
            }

            var sourceparent = System.Windows.Controls.ItemsControl.ItemsControlFromItemContainer(sourceItem) as System.Windows.Controls.TabControl;

            var target = parent.ItemContainerGenerator.ItemFromContainer(targetItem);
            IList list = parent.GetActualList();
            int indexTarget = list.IndexOf(target);
            if (parent == sourceparent)
            {
                var source = parent.ItemContainerGenerator.ItemFromContainer(sourceItem);

                list.Remove(source);
                list.Insert(indexTarget, source);
            }
            else
            {
                var source = sourceparent.ItemContainerGenerator.ItemFromContainer(sourceItem);
                IList soureclist = sourceparent.GetActualList();
                soureclist.Remove(source);
                if (soureclist.Count == 0)
                {
                    sourceparent.MinTabControl();
                }
                else
                {
                    sourceparent.SelectedIndex = 0;
                }

                list.Insert(indexTarget, source);

                
            }

            sourceItem.IsSelected = true;
            if (sourceItem.OriParent == null)
            {
                sourceItem.OriParent = sourceparent;
            }
            

            e.Handled = true;
        }

    }

    public static class TabItemHelper
    {
        internal static IList GetActualList(this System.Windows.Controls.TabControl tabControl)
        {
            IList list;
            if (tabControl.ItemsSource != null)
            {
                list = tabControl.ItemsSource as IList;
            }
            else
            {
                list = tabControl.Items;
            }

            return list;
        }

        internal static void MinTabControl(this System.Windows.Controls.TabControl tabControl)
        {
            var grid = tabControl.Tag as Grid;
            if (grid != null)
            {
                var row = Grid.GetRow(tabControl);
                for (int i = 0; i < grid.RowDefinitions.Count; i++)
                {
                    if (i == row)
                    {
                        grid.RowDefinitions[i].Height = new System.Windows.GridLength(0, GridUnitType.Auto);
                    }
                    else 
                    {
                        var tag = grid.RowDefinitions[i].Tag == null? "": grid.RowDefinitions[i].Tag.ToString();
                        string[] info = tag.Split('_');
                        if (info.Length == 2)
                        {
                            double length;
                            if (double.TryParse(info[0], out length) && info[1] == "Star")
                            {
                                grid.RowDefinitions[i].Height = new System.Windows.GridLength(length, GridUnitType.Star);
                            }
                        }                            
                    }
                }
            }
        }

        internal static void ResetTabControl(this System.Windows.Controls.TabControl tabControl)
        {
            var grid = tabControl.Tag as Grid;
            if (grid != null)
            {
                for (int i = 0; i < grid.RowDefinitions.Count; i++)
                {
                    var tag = grid.RowDefinitions[i].Tag == null ? "" : grid.RowDefinitions[i].Tag.ToString();
                    string[] info = tag.Split('_');
                    if (info.Length == 2)
                    {
                        double length;
                        if (double.TryParse(info[0], out length) && info[1] == "Star")
                        {
                            grid.RowDefinitions[i].Height = new System.Windows.GridLength(length, GridUnitType.Star);
                        }
                    }
                }
            }
        }
    }

    public static class ControlCommands
    {
        /// <summary>
        ///     窗外窗
        /// </summary>
        public static RoutedCommand SingleWindowCommand { get; } = new RoutedCommand(nameof(SingleWindowCommand), typeof(ControlCommands));
        /// <summary>
        ///     MDI窗口
        /// </summary>
        public static RoutedCommand SingleMDIWindowCommand { get; } = new RoutedCommand(nameof(SingleMDIWindowCommand), typeof(ControlCommands));

    }
}
